<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WhuOps 智能运维平台</title>
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css">
    <script src="//unpkg.com/vue@3"></script>
    <script src="//unpkg.com/element-plus"></script>
    <script src="//unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        }

        .app-container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background-color: #001529;
            color: white;
            padding: 20px 0;
        }

        .sidebar-header {
            padding: 0 20px;
            margin-bottom: 20px;
        }

        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-menu li {
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .sidebar-menu li:hover {
            background-color: #1890ff;
        }

        .sidebar-menu li.active {
            background-color: #1890ff;
        }

        .main-content {
            flex: 1;
            padding: 20px;
            background-color: #f0f2f5;
        }

        .content-section {
            display: none;
            background: white;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .content-section.active {
            display: block;
        }

        .chat-container {
            height: 500px;
            border: 1px solid #e8e8e8;
            border-radius: 4px;
            display: flex;
            flex-direction: column;
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
        }

        .message {
            margin-bottom: 15px;
            display: flex;
            flex-direction: column;
        }

        .message.user {
            align-items: flex-end;
        }

        .message.assistant {
            align-items: flex-start;
        }

        .message-content {
            max-width: 70%;
            padding: 10px 15px;
            border-radius: 4px;
            word-wrap: break-word;
        }

        .message.user .message-content {
            background-color: #1890ff;
            color: white;
        }

        .message.assistant .message-content {
            background-color: #f0f2f5;
        }

        .chat-input {
            padding: 20px;
            border-top: 1px solid #e8e8e8;
            display: flex;
            gap: 10px;
        }

        .chat-input input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
        }

        .chat-input button {
            padding: 8px 16px;
            background-color: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .chat-input button:hover {
            background-color: #40a9ff;
        }

        .container {
            padding: 20px;
        }

        .header {
            margin-bottom: 20px;
        }

        .content {
            background: #fff;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .dashboard-card {
            margin-bottom: 20px;
            cursor: pointer;
        }

        .dashboard-card:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        /* Prometheus 指标查询相关样式 */
        .metric-card {
            margin-bottom: 20px;
        }

        .metric-content {
            padding: 20px;
        }

        .metric-form {
            margin-bottom: 20px;
        }

        .metric-results {
            margin-top: 20px;
        }

        .metric-results .el-table {
            margin-top: 10px;
        }

        .metric-results .el-table .cell {
            white-space: pre-wrap;
            word-break: break-word;
        }

        /* 故障监控相关样式 */
        .fault-card {
            margin-bottom: 20px;
        }

        .fault-card .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .fault-content {
            padding: 20px;
        }

        .fault-content .el-alert {
            margin-bottom: 20px;
        }

        .fault-content .el-table {
            margin-top: 20px;
        }

        .fault-content .el-tag {
            margin-right: 8px;
        }

        .fault-content .el-tag--success {
            background-color: #f0f9eb;
            border-color: #e1f3d8;
            color: #67c23a;
        }

        .fault-content .el-tag--danger {
            background-color: #fef0f0;
            border-color: #fde2e2;
            color: #f56c6c;
        }

        .update-time {
            font-size: 12px;
            color: #909399;
        }

        /* 展开行动画 */
        .expand-transition {
            transition: max-height 0.3s ease-out;
            max-height: 0;
            overflow: hidden;
        }

        .expand-transition.expanded {
            max-height: 500px;
        }

        .expand-card {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.06);
            padding: 18px 18px 8px 18px;
            margin: 8px 0;
        }

        .expand-inner-table {
            font-size: 13px;
            border-radius: 6px;
        }

        .expand-inner-table .el-table__header th {
            background: #f5f7fa;
            color: #606266;
            font-weight: 500;
            border-radius: 6px 6px 0 0;
        }

        .expand-inner-table .el-table__row {
            height: 36px;
        }

        .status-cell {
            font-weight: bold;
            padding: 2px 10px;
            border-radius: 4px;
        }

        .status-cell.normal {
            color: #67c23a;
            background: #f0f9eb;
        }

        .status-cell.abnormal {
            color: #f56c6c;
            background: #fef0f0;
        }

        .expand-inner-table .el-table__row.abnormal {
            background: #fff6f6;
        }
    </style>
</head>
<body>
<div id="app">
    <div class="app-container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>WhuOps</h2>
            </div>
            <ul class="sidebar-menu">
                <li :class="{ active: activeSection === 'chat' }" @click="handleSectionClick('chat')">AI 聊天</li>
                <li :class="{ active: activeSection === 'agent' }" @click="handleSectionClick('agent')">AI 助手</li>
                <li :class="{ active: activeSection === 'monitor' }" @click="handleSectionClick('monitor')">集群监控
                </li>
                <li :class="{ active: activeSection === 'fault' }" @click="handleSectionClick('fault')">故障监控</li>
            </ul>
        </div>
        <div class="main-content">
            <!-- AI 聊天部分 -->
            <div class="content-section" :class="{ active: activeSection === 'chat' }">
                <h2>AI K8S集群诊断专家</h2>
                <div class="chat-container">
                    <div class="chat-messages" ref="chatMessagesRef">
                        <div v-for="(message, index) in chatMessages" :key="index"
                             :class="['message', message.type]">
                            <div class="message-content">{{ message.content }}</div>
                        </div>
                    </div>
                    <div class="chat-input">
                        <input type="text" v-model="chatInput" @keyup.enter="sendChatMessage"
                               placeholder="请输入您的问题...">
                        <button @click="sendChatMessage">发送</button>
                    </div>
                </div>
            </div>

            <!-- AI 助手部分 -->
            <div class="content-section" :class="{ active: activeSection === 'agent' }">
                <h2>AI 助手</h2>
                <div class="chat-container">
                    <div class="chat-messages" ref="agentMessagesRef">
                        <div v-for="(message, index) in agentMessages" :key="index"
                             :class="['message', message.type]">
                            <div class="message-content">{{ message.content }}</div>
                        </div>
                    </div>
                    <div class="chat-input">
                        <input type="text" v-model="agentInput" @keyup.enter="sendAgentMessage"
                               placeholder="请输入指令，例如：打开微信、查看天气、查询k8s集群...">
                        <button @click="sendAgentMessage">发送</button>
                    </div>
                </div>
            </div>

            <!-- 集群监控部分 -->
            <div class="content-section" :class="{ active: activeSection === 'monitor' }">
                <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                    <el-tab-pane label="Grafana仪表板" name="grafana">
                        <div class="content">
                            <el-row :gutter="20">
                                <el-col :span="8" v-for="dashboard in dashboards" :key="dashboard.uid">
                                    <el-card class="dashboard-card" @click="openDashboard(dashboard)">
                                        <template #header>
                                            <div class="card-header">
                                                <span>{{ dashboard.title }}</span>
                                            </div>
                                        </template>
                                        <div class="card-content">
                                            <p>类型: {{ dashboard.type }}</p>
                                            <p>标签: {{ dashboard.tags ? dashboard.tags.join(', ') : '无' }}</p>
                                        </div>
                                    </el-card>
                                </el-col>
                            </el-row>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="Prometheus指标" name="prometheus">
                        <div class="content">
                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-card class="metric-card">
                                        <template #header>
                                            <div class="card-header">
                                                <span>Prometheus指标查询</span>
                                            </div>
                                        </template>
                                        <div class="metric-content">
                                            <el-form :inline="true" class="metric-form">
                                                <el-form-item label="指标名称">
                                                    <el-select
                                                            v-model="selectedMetric"
                                                            placeholder="选择指标"
                                                            filterable
                                                            @change="handleMetricChange"
                                                            style="width: 400px">
                                                        <el-option
                                                                v-for="metric in availableMetrics"
                                                                :key="metric"
                                                                :label="metric"
                                                                :value="metric">
                                                        </el-option>
                                                    </el-select>
                                                </el-form-item>

                                                <!-- 动态参数选择 -->
                                                <template v-if="metricParams.length > 0">
                                                    <el-form-item v-for="param in metricParams" :key="param.name"
                                                                  :label="param.label">
                                                        <el-select
                                                                v-if="param.type === 'select'"
                                                                v-model="param.value"
                                                                :placeholder="'选择' + param.label"
                                                                filterable
                                                                clearable>
                                                            <el-option
                                                                    v-for="option in param.options"
                                                                    :key="option"
                                                                    :label="option"
                                                                    :value="option">
                                                            </el-option>
                                                        </el-select>
                                                        <el-input
                                                                v-else-if="param.type === 'input'"
                                                                v-model="param.value"
                                                                :placeholder="'输入' + param.label">
                                                        </el-input>
                                                    </el-form-item>
                                                </template>

                                                <el-form-item>
                                                    <el-button type="primary" @click="queryMetrics">查询</el-button>
                                                    <el-button @click="resetQuery">重置</el-button>
                                                </el-form-item>
                                            </el-form>

                                            <div v-if="metricResults.length > 0" class="metric-results">
                                                <el-table :data="metricResults" style="width: 100%">
                                                    <el-table-column prop="metric" label="指标标签" min-width="300">
                                                        <template #default="scope">
                                                            <div v-for="(value, key) in scope.row.metric" :key="key">
                                                                {{ key }}: {{ value }}
                                                            </div>
                                                        </template>
                                                    </el-table-column>
                                                    <el-table-column prop="value" label="值" width="150">
                                                        <template #default="scope">
                                                            {{ formatMetricValue(scope.row.value) }}
                                                        </template>
                                                    </el-table-column>
                                                    <el-table-column prop="timestamp" label="时间戳" width="180">
                                                        <template #default="scope">
                                                            {{ formatTimestamp(scope.row.timestamp) }}
                                                        </template>
                                                    </el-table-column>
                                                </el-table>
                                            </div>
                                        </div>
                                    </el-card>
                                </el-col>
                            </el-row>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="Kubernetes节点" name="nodes">
                        <div class="content">
                            <el-table :data="nodes" style="width: 100%">
                                <el-table-column prop="name" label="名称"></el-table-column>
                                <el-table-column label="状态" width="100">
                                    <template #default="scope">
                                        <el-tag :type="scope.row.status === 'normal' ? 'success' : 'danger'">
                                            {{ scope.row.status === 'normal' ? '正常' : '异常' }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="message" label="说明"></el-table-column>
                            </el-table>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="Kubernetes Pods" name="pods">
                        <div class="content">
                            <el-table :data="podsDetail" style="width: 100%">
                                <el-table-column prop="name" label="名称"></el-table-column>
                                <el-table-column prop="namespace" label="命名空间"></el-table-column>
                                <el-table-column label="状态" width="100">
                                    <template #default="scope">
                                        <el-tag :type="scope.row.status === 'normal' ? 'success' : 'danger'">
                                            {{ scope.row.status === 'normal' ? '正常' : '异常' }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="phase" label="阶段"></el-table-column>
                                <el-table-column prop="message" label="说明"></el-table-column>
                            </el-table>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="Kubernetes事件" name="events">
                        <div class="content">
                            <el-table :data="events" style="width: 100%">
                                <el-table-column prop="metadata.name" label="名称"></el-table-column>
                                <el-table-column prop="type" label="类型"></el-table-column>
                                <el-table-column prop="reason" label="原因"></el-table-column>
                                <el-table-column prop="message" label="消息"></el-table-column>
                            </el-table>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>

            <!-- 故障监控部分 -->
            <div class="content-section" :class="{ active: activeSection === 'fault' }">
                <h2>故障监控</h2>
                <div class="content">
                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-card class="fault-card">
                                <template #header>
                                    <div class="card-header">
                                        <span>集群状态概览</span>
                                        <div>
                                            <el-tag type="info" style="margin-right: 10px">
                                                最后更新: {{ formatUpdateTime(faultStatus.lastUpdate) }}
                                            </el-tag>
                                            <el-button type="primary" size="small" @click="refreshFaultStatus">刷新
                                            </el-button>
                                        </div>
                                    </div>
                                </template>
                                <div class="fault-content">
                                    <el-alert
                                            v-if="faultStatus.hasFault"
                                            :title="faultStatus.message"
                                            type="error"
                                            :description="faultStatus.details"
                                            show-icon>
                                    </el-alert>
                                    <el-alert
                                            v-else
                                            title="系统运行正常"
                                            type="success"
                                            description="所有指标均在正常范围内"
                                            show-icon>
                                    </el-alert>
                                </div>
                            </el-card>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20" style="margin-top: 20px;">
                        <el-col :span="24">
                            <el-card class="fault-card">
                                <template #header>
                                    <div class="card-header">
                                        <span>详细指标</span>
                                        <el-tag type="info">自动刷新间隔: {{ Math.round(refreshIntervalMs / 1000) }}秒
                                        </el-tag>
                                    </div>
                                </template>
                                <div class="fault-content">
                                    <el-table
                                            :data="faultMetrics"
                                            style="width: 100%"
                                            v-loading="!faultMetrics.length"
                                            row-key="name"
                                            v-model:expand-row-keys="expandRowKeys"
                                    >
                                        <el-table-column type="expand">
                                            <template #default="props">
                                                <div v-if="props.row.name === '节点状态'" class="expand-card">
                                                    <el-table :data="nodes" size="small" :border="false"
                                                              class="expand-inner-table">
                                                        <el-table-column prop="name" label="节点名称"></el-table-column>
                                                        <el-table-column prop="status" label="状态" width="100">
                                                            <template #default="scope">
                                                                <el-tag :type="scope.row.status === 'normal' ? 'success' : 'danger'"
                                                                        effect="light">
                                                                    {{ scope.row.status === 'normal' ? '正常' : '异常'
                                                                    }}
                                                                </el-tag>
                                                            </template>
                                                        </el-table-column>
                                                        <el-table-column prop="message" label="说明"></el-table-column>
                                                        <el-table-column label="修复项" width="180">
                                                            <template #default="scope">
                                                                <el-button
                                                                        :type="scope.row.status === 'normal' ? 'info' : 'success'"
                                                                        size="small"
                                                                        :disabled="scope.row.status === 'normal'"
                                                                >手动修复
                                                                </el-button>
                                                                <el-button
                                                                        :type="scope.row.status === 'normal' ? 'info' : 'success'"
                                                                        size="small"
                                                                        :disabled="scope.row.status === 'normal'"
                                                                        style="margin-left: 8px;"
                                                                >自动修复
                                                                </el-button>
                                                            </template>
                                                        </el-table-column>
                                                    </el-table>
                                                </div>
                                                <!-- 在 el-table-column type="expand" 的模板中，替换 Pod状态 部分 -->
                                                <div v-else-if="props.row.name === 'Pod状态'" class="expand-card">
                                                    <div class="namespace-table">
                                                        <h4 style="margin-bottom: 15px; color: #333;">命名空间列表</h4>
                                                        <div v-for="namespace in namespaceList" :key="namespace.name"
                                                             class="namespace-item">
                                                            <div
                                                                    :class="['namespace-row', { 'namespace-expanded': namespace.expanded }]"
                                                                    @click="toggleNamespace(namespace)"
                                                                    style="padding: 12px; border: 1px solid #e8e8e8; border-radius: 6px; margin-bottom: 8px; cursor: pointer;"
                                                            >
                                                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                                                    <div style="display: flex; align-items: center;">
                                                                        <i style="margin-right: 8px; transition: transform 0.3s; color: #1890ff;"
                                                                           :style="{ transform: namespace.expanded ? 'rotate(90deg)' : 'rotate(0deg)' }">▶</i>
                                                                        <strong>{{ namespace.name }}</strong>
                                                                    </div>
                                                                    <div style="display: flex; gap: 10px; align-items: center;">
                                                                        <el-tag size="small" type="info">Pod总数: {{
                                                                            namespace.totalPods }}
                                                                        </el-tag>
                                                                        <el-tag size="small"
                                                                                :type="namespace.abnormalPods > 0 ? 'danger' : 'success'">
                                                                            异常: {{ namespace.abnormalPods }}
                                                                        </el-tag>
                                                                    </div>
                                                                </div>
                                                            </div>

                                                            <!-- 展开显示Pod列表 -->
                                                            <div v-if="namespace.expanded"
                                                                 style="margin-top: 15px; padding: 15px; background-color: #fafafa; border-radius: 6px;">
                                                                <div style="margin-bottom: 15px; font-weight: 600; color: #333;">
                                                                    {{ namespace.name }} 命名空间下的 Pod 列表
                                                                </div>
                                                                <div v-for="pod in namespace.pods" :key="pod.name"
                                                                     style="display: flex; justify-content: space-between; align-items: center; padding: 8px 12px; margin-bottom: 8px; background: white; border-radius: 4px; border: 1px solid #e8e8e8;">
                                                                    <div style="flex: 1;">
                                                                        <div style="font-weight: 500; color: #333; margin-bottom: 4px;">
                                                                            {{ pod.name }}
                                                                        </div>
                                                                        <div style="font-size: 12px; color: #666;">阶段:
                                                                            {{ pod.phase }} | {{ pod.message }}
                                                                        </div>
                                                                    </div>
                                                                    <div style="display: flex; gap: 8px; align-items: center;">
                                                                        <el-tag :type="pod.status === 'normal' ? 'success' : 'danger'"
                                                                                effect="light" size="small">
                                                                            {{ pod.status === 'normal' ? '正常' : '异常'
                                                                            }}
                                                                        </el-tag>
                                                                        <el-button
                                                                                :type="pod.status === 'normal' ? 'info' : 'warning'"
                                                                                size="small"
                                                                                :disabled="pod.status === 'normal'">
                                                                            修复
                                                                        </el-button>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="name" label="指标名称" min-width="180"></el-table-column>
                                        <el-table-column prop="value" label="当前值" min-width="120"></el-table-column>
                                        <el-table-column prop="threshold" label="阈值"
                                                         min-width="120"></el-table-column>
                                        <el-table-column prop="status" label="状态" width="100">
                                            <template #default="scope">
                                                <el-tag :type="scope.row.status === 'normal' ? 'success' : 'danger'">
                                                    {{ scope.row.status === 'normal' ? '正常' : '异常' }}
                                                </el-tag>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="message" label="说明" min-width="200"></el-table-column>
                                    </el-table>
                                </div>
                            </el-card>
                        </el-col>
                    </el-row>
                </div>
            </div>
        </div>
    </div>

    <!-- 日志对话框 -->
    <el-dialog v-model="logDialogVisible" title="Pod日志" width="70%">
        <pre style="background: #f5f7fa; padding: 10px; border-radius: 4px;">{{ podLogs }}</pre>
    </el-dialog>
</div>

<script>
    const {createApp, ref, onMounted, nextTick, computed, onUnmounted, watch} = Vue;
    const app = createApp({
        setup() {
            const activeSection = ref('chat');
            const activeTab = ref('grafana');
            const chatInput = ref('');
            const agentInput = ref('');
            const chatMessages = ref([]);
            const agentMessages = ref([]);
            const chatMessagesRef = ref(null);
            const agentMessagesRef = ref(null);
            const dashboards = ref([]);
            const grafanaBaseUrl = ref('');
            const pods = ref([]);
            const events = ref([]);
            const logDialogVisible = ref(false);
            const podLogs = ref('');
            const selectedMetric = ref('');
            const metricParams = ref([]);
            const metricResults = ref([]);
            const availableMetrics = ref([]);
            const faultStatus = ref({
                hasFault: false,
                message: '',
                details: '',
                lastUpdate: null
            });
            const faultMetrics = ref([]);
            let refreshInterval = null;
            const refreshIntervalMs = ref(20000); // 默认20秒
            const nodes = ref([]);
            const podsDetail = ref([]);
            const nodeSummary = ref({total: 0, abnormal: 0});
            const podSummary = ref({total: 0, abnormal: 0});
            const expandRowKeys = ref([]);

            const namespaceList = ref([]);

            // 新增函数：切换命名空间展开状态
            const toggleNamespace = (namespace) => {
                namespace.expanded = !namespace.expanded;
            };

// 修改 fetchPodsDetail 函数，按命名空间分组
            const fetchPodsDetail = async () => {
                try {
                    const res = await axios.get('/api/monitor/k8s/pods/detail');
                    podsDetail.value = res.data;

                    // 按命名空间分组Pod数据
                    const namespaceMap = {};
                    res.data.forEach(pod => {
                        if (!namespaceMap[pod.namespace]) {
                            namespaceMap[pod.namespace] = {
                                name: pod.namespace,
                                pods: [],
                                totalPods: 0,
                                abnormalPods: 0,
                                expanded: false
                            };
                        }
                        namespaceMap[pod.namespace].pods.push(pod);
                        namespaceMap[pod.namespace].totalPods++;
                        if (pod.status === 'abnormal') {
                            namespaceMap[pod.namespace].abnormalPods++;
                        }
                    });

                    namespaceList.value = Object.values(namespaceMap);

                    podSummary.value.total = res.data.length;
                    podSummary.value.abnormal = res.data.filter(p => p.status === 'abnormal').length;
                } catch (error) {
                    ElMessage.error('获取Pod详情失败：' + error.message);
                }
            };

            const scrollToBottom = async (ref) => {
                await nextTick();
                if (ref.value) {
                    ref.value.scrollTop = ref.value.scrollHeight;
                }
            };

            const sendChatMessage = async () => {
                if (!chatInput.value.trim()) return;

                chatMessages.value.push({
                    type: 'user',
                    content: chatInput.value
                });

                const userInput = chatInput.value;
                chatInput.value = '';
                await scrollToBottom(chatMessagesRef);

                try {
                    chatMessages.value.push({
                        type: 'assistant',
                        content: ''
                    });

                    const eventSource = new EventSource(`http://127.0.0.1:3210/ai/finalResp?message=${encodeURIComponent(userInput)}&sessionId=1234`);

                    eventSource.onmessage = (event) => {
                        const content = event.data;
                        const lastMessage = chatMessages.value[chatMessages.value.length - 1];
                        lastMessage.content += content;
                        scrollToBottom(chatMessagesRef);
                    };

                    eventSource.onerror = () => {
                        eventSource.close();
                    };
                } catch (error) {
                    chatMessages.value.push({
                        type: 'assistant',
                        content: '抱歉，发生了错误：' + error.message
                    });
                    await scrollToBottom(chatMessagesRef);
                }
            };

            const sendAgentMessage = async () => {
                if (!agentInput.value.trim()) return;

                agentMessages.value.push({
                    type: 'user',
                    content: agentInput.value
                });

                const userInput = agentInput.value;
                agentInput.value = '';
                await scrollToBottom(agentMessagesRef);

                try {
                    agentMessages.value.push({
                        type: 'assistant',
                        content: '正在处理请求...'
                    });

                    console.log('发送请求到:', `http://127.0.0.1:3210/ai/agent/process?command=${encodeURIComponent(userInput)}`);
                    const response = await fetch(`http://127.0.0.1:3210/ai/agent/process?command=${encodeURIComponent(userInput)}`);

                    console.log('响应状态:', response.status, response.statusText);
                    const responseClone = response.clone();

                    try {
                        const responseBody = await responseClone.text();
                        console.log('原始响应内容:', responseBody);
                    } catch (e) {
                        console.log('读取响应体失败:', e);
                    }

                    if (!response.ok) {
                        throw new Error(`服务器返回错误状态: ${response.status} ${response.statusText}`);
                    }

                    const result = await response.text();
                    console.log('处理后响应:', result);

                    // 更新最后一条消息的内容
                    const lastMessage = agentMessages.value[agentMessages.value.length - 1];
                    lastMessage.content = result;
                    await scrollToBottom(agentMessagesRef);
                } catch (error) {
                    console.error('发生错误:', error);
                    // 如果出错，更新最后一条消息
                    if (agentMessages.value.length > 0 && agentMessages.value[agentMessages.value.length - 1].type === 'assistant') {
                        agentMessages.value[agentMessages.value.length - 1].content = '抱歉，发生了错误：' + error.message;
                    } else {
                        agentMessages.value.push({
                            type: 'assistant',
                            content: '抱歉，发生了错误：' + error.message
                        });
                    }
                    await scrollToBottom(agentMessagesRef);
                }
            };

            const loadGrafanaUrl = async () => {
                try {
                    const response = await axios.get('/api/monitor/grafana/url');
                    if (response.data && response.data.url) {
                        grafanaBaseUrl.value = response.data.url;
                    } else {
                        ElMessage.error('无法获取 Grafana URL');
                    }
                } catch (error) {
                    ElMessage.error('加载 Grafana URL 失败: ' + error.message);
                }
            };

            const loadDashboards = async () => {
                try {
                    const response = await axios.get('/api/monitor/grafana/search');
                    if (response.data && response.data.length > 0) {
                        dashboards.value = response.data;
                        ElMessage.success(`成功加载 ${dashboards.value.length} 个仪表板`);
                    } else {
                        ElMessage.warning('没有找到可用的仪表板');
                    }
                } catch (error) {
                    ElMessage.error('加载仪表板失败：' + error.message);
                }
            };

            const loadPods = async () => {
                try {
                    const response = await axios.get('/api/monitor/k8s/pods');
                    pods.value = response.data;
                } catch (error) {
                    ElMessage.error('加载Pods失败：' + error.message);
                }
            };

            const loadEvents = async () => {
                try {
                    const response = await axios.get('/api/monitor/k8s/events');
                    events.value = response.data;
                } catch (error) {
                    ElMessage.error('加载事件失败：' + error.message);
                }
            };

            const viewPodLogs = async (podName) => {
                try {
                    const response = await axios.get(`/api/monitor/k8s/pods/${podName}/logs`);
                    podLogs.value = response.data;
                    logDialogVisible.value = true;
                } catch (error) {
                    ElMessage.error('获取Pod日志失败：' + error.message);
                }
            };

            const openDashboard = (dashboard) => {
                if (!dashboard || !dashboard.uid) {
                    ElMessage.error('无效的仪表板信息');
                    return;
                }
                if (!grafanaBaseUrl.value) {
                    ElMessage.error('Grafana URL 未加载，请稍后再试');
                    return;
                }
                const dashboardUrl = `${grafanaBaseUrl.value}/d/${dashboard.uid}`;
                window.open(dashboardUrl, '_blank');
            };

            const handleTabClick = (tab) => {
                switch (tab.props.name) {
                    case 'grafana':
                        loadDashboards();
                        break;
                    case 'nodes':
                        fetchNodes();
                        break;
                    case 'pods':
                        fetchPodsDetail();
                        break;
                    case 'events':
                        loadEvents();
                        break;
                }
            };

            const handleSectionClick = (section) => {
                activeSection.value = section;
                if (section === 'monitor') {
                    loadGrafanaUrl();
                    loadDashboards();
                    loadAvailableMetrics();
                    stopAutoRefresh();
                } else if (section === 'fault') {
                    refreshFaultStatus();
                    startAutoRefresh();
                    fetchNodes();
                    fetchPodsDetail();
                } else {
                    stopAutoRefresh();
                }
            };

            const loadAvailableMetrics = async () => {
                try {
                    const response = await axios.get('/api/monitor/prometheus/metric-names');
                    if (response.data && Array.isArray(response.data.data)) {
                        availableMetrics.value = response.data.data;
                    } else {
                        availableMetrics.value = [];
                    }
                } catch (error) {
                    ElMessage.error('加载指标列表失败：' + error.message);
                }
            };

            const handleMetricChange = async (metric) => {
                if (!metric) {
                    metricParams.value = [];
                    return;
                }
                // 这里可以根据实际需要动态加载参数
                metricParams.value = [];
                if (metric.includes('container')) {
                    metricParams.value.push({
                        name: 'container',
                        label: '容器名称',
                        type: 'input',
                        value: ''
                    });
                }
                if (metric.includes('pod')) {
                    metricParams.value.push({
                        name: 'pod',
                        label: 'Pod名称',
                        type: 'input',
                        value: ''
                    });
                }
                if (metric.includes('namespace')) {
                    metricParams.value.push({
                        name: 'namespace',
                        label: '命名空间',
                        type: 'input',
                        value: ''
                    });
                }
            };

            const buildQuery = () => {
                let query = selectedMetric.value;
                if (metricParams.value.length > 0) {
                    const conditions = metricParams.value
                        .filter(param => param.value)
                        .map(param => `${param.name}=\"${param.value}\"`)
                        .join(',');
                    if (conditions) {
                        query = `${query}{${conditions}}`;
                    }
                }
                return query;
            };

            const queryMetrics = async () => {
                try {
                    const query = buildQuery();
                    if (!query) {
                        ElMessage.warning('请选择指标');
                        return;
                    }
                    const response = await axios.get(`/api/monitor/prometheus/metrics?query=${query}`);
                    // 这里假设后端返回 { data: { result: [...] } }
                    if (response.data && response.data.data && Array.isArray(response.data.data.result)) {
                        metricResults.value = response.data.data.result.map(item => ({
                            metric: item.metric,
                            value: Array.isArray(item.value) ? item.value[1] : item.value,
                            timestamp: Array.isArray(item.value) ? item.value[0] : undefined
                        }));
                    } else {
                        metricResults.value = [];
                    }
                    if (metricResults.value.length === 0) {
                        ElMessage.info('没有找到匹配的指标数据');
                    }
                } catch (error) {
                    ElMessage.error('查询指标失败：' + error.message);
                }
            };

            const resetQuery = () => {
                selectedMetric.value = '';
                metricParams.value = [];
                metricResults.value = [];
            };

            const formatMetricValue = (value) => {
                if (typeof value === 'number') {
                    return value.toFixed(2);
                }
                return value;
            };

            const formatTimestamp = (timestamp) => {
                if (!timestamp) return '';
                // Prometheus 时间戳是秒
                return new Date(timestamp * 1000).toLocaleString();
            };

            const formatUpdateTime = (timestamp) => {
                if (!timestamp) return '未更新';
                const date = new Date(timestamp);
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                    hour12: false
                });
            };

            const refreshFaultStatus = async () => {
                try {
                    const response = await axios.get('/api/monitor/fault/status');
                    faultStatus.value = response.data;
                    // 保证name字段为字符串且去除首尾空格
                    faultMetrics.value = response.data.metrics.map(item => ({
                        ...item,
                        name: String(item.name).trim()
                    }));
                    if (response.data.refreshInterval) {
                        refreshIntervalMs.value = response.data.refreshInterval;
                    }
                    // 保持已展开的行（全部转为字符串并trim）
                    expandRowKeys.value = expandRowKeys.value
                        .map(key => String(key).trim())
                        .filter(key => faultMetrics.value.some(item => item.name === key));
                } catch (error) {
                    ElMessage.error('获取故障状态失败：' + error.message);
                }
            };

            const startAutoRefresh = () => {
                if (refreshInterval) {
                    clearInterval(refreshInterval);
                }
                refreshInterval = setInterval(refreshFaultStatus, refreshIntervalMs.value);
            };

            const stopAutoRefresh = () => {
                if (refreshInterval) {
                    clearInterval(refreshInterval);
                    refreshInterval = null;
                }
            };

            // 获取节点详细信息
            const fetchNodes = async () => {
                try {
                    const res = await axios.get('/api/monitor/k8s/nodes/detail');
                    nodes.value = res.data;
                    nodeSummary.value.total = res.data.length;
                    nodeSummary.value.abnormal = res.data.filter(n => n.status === 'abnormal').length;
                } catch (error) {
                    ElMessage.error('获取节点详情失败：' + error.message);
                }
            };

            // // 获取Pod详细信息
            // const fetchPodsDetail = async () => {
            //     try {
            //         const res = await axios.get('/api/monitor/k8s/pods/detail');
            //         podsDetail.value = res.data;
            //         podSummary.value.total = res.data.length;
            //         podSummary.value.abnormal = res.data.filter(p => p.status === 'abnormal').length;
            //     } catch (error) {
            //         ElMessage.error('获取Pod详情失败：' + error.message);
            //     }
            // };

            onMounted(() => {
                // 初始加载
                loadGrafanaUrl();
                loadDashboards();
            });

            onUnmounted(() => {
                stopAutoRefresh();
            });

            return {
                namespaceList,
                toggleNamespace,
                activeSection,
                activeTab,
                chatInput,
                agentInput,
                chatMessages,
                agentMessages,
                chatMessagesRef,
                agentMessagesRef,
                dashboards,
                grafanaBaseUrl,
                pods,
                events,
                logDialogVisible,
                podLogs,
                selectedMetric,
                metricParams,
                metricResults,
                availableMetrics,
                faultStatus,
                faultMetrics,
                refreshIntervalMs,
                nodes,
                podsDetail,
                nodeSummary,
                podSummary,
                handleSectionClick,
                sendChatMessage,
                sendAgentMessage,
                openDashboard,
                handleTabClick,
                queryMetrics,
                resetQuery,
                formatMetricValue,
                formatTimestamp,
                formatUpdateTime,
                refreshFaultStatus,
                expandRowKeys
            };
        }
    });

    app.use(ElementPlus);
    app.mount('#app');
</script>
</body>
</html>
